package com.aceitunaproject.server.settlement;

import java.io.Serializable;
import java.util.logging.Logger;

import com.aceitunaproject.server.AceitunaContext;
import com.aceitunaproject.server.entity.settlement.Settlement;
import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.ManagedObject;
import com.sun.sgs.app.ManagedReference;
import com.sun.sgs.app.Task;

public class SettlementRefreshTask implements Task, ManagedObject, Serializable {

	private static final long serialVersionUID = 4510509634430440799L;
	/**
	 * The settlement to refresh
	 */
	private ManagedReference<Settlement> settlement;

	private double tickAtLastUpdate;

	@Override
	public void run() throws Exception {

		Settlement theSettlement = settlement.get();

		
		double tmpCurTick = AceitunaContext.getTickManager().getCurrentTick();
		if (tickAtLastUpdate != tmpCurTick) {
			Logger.getLogger(this.getClass().getName()).info(
					"refreshing settlement " + theSettlement.getName());
			theSettlement.refreshPopulation();
			AppContext.getDataManager().markForUpdate(this);
			tickAtLastUpdate = tmpCurTick;
		}

	}

	public SettlementRefreshTask(Settlement settlement) {
		this.settlement = AppContext.getDataManager().createReference(
				settlement);
	}

}
